package be.webchess.www.actions.ajax;

import be.webchess.www.logic.impl.ChessGameLogic;
import be.webchess.www.model.ChessBoard;
import be.webchess.www.model.ChessPiece;
import be.webchess.www.service.IChessBoardService;
import be.webchess.www.service.IChessPieceService;
import be.webchess.www.service.impl.ChessBoardService;
import be.webchess.www.service.impl.ChessPieceService;

public class AjaxMoveAction extends AjaxBaseAction {

	private IChessBoardService		cbServ;
	private IChessPieceService		cpServ;
	private ChessBoard				cb;
	private ChessGameLogic			logic;
	private boolean					hasMoved = false;
	
	public AjaxMoveAction() {
		// TODO Auto-generated constructor stub
	}

	public String execute ()
	{
		
		try
		{
			String		from, to;
			
			if ( request.getParameter("chessboard_id") == null || request.getParameter("from") == null || request.getParameter("to") == null )
			{
				this.addActionError("Invalid action");
				return ERROR;
			}			
			
			from = request.getParameter("from");
			to = request.getParameter("to");
			
			Long cb_id = Long.parseLong(request.getParameter("chessboard_id"));
			
			cbServ = new ChessBoardService(connection);
			cpServ = new ChessPieceService(connection);
			
			cb = cbServ.findByID(cb_id);
			
			logic = new ChessGameLogic(cb);
									
			hasMoved = logic.movePiece(from, to);
						
			if ( hasMoved )
			{
				ChessPiece	p = cb.getMatrix().get(to);
				
				cpServ.update(p);
								
				p = cb.getMatrix().get("00");
				
				if ( p != null )
					cpServ.update(p);
				
				logic.toggleCurrentPlayer();
				
				cbServ.update(cb);
			}
			
		} catch ( Exception ex )
		{
			this.addActionError(ex.getMessage());
			return ERROR;
		}		
		
		return SUCCESS;
	}
	
	@Override
	public String getContent() {
		// TODO Auto-generated method stub
		if ( hasMoved )
			return "true";
		else
			return "false";
	}

}
